# 首先将所有的gz文件解压出来
# gzip -dv access.log.*.gz

# import os,sys                       #导入模块
# def add_prefix_subfolders():        #定义函数名称
#     mark = 'test-'                  #准备添加的前缀内容
#     old_names = os.listdir( path )  #取路径下的文件名，生成列表
#     for old_name in old_names:      #遍历列表下的文件名
#         if old_name!= sys.argv[0]:     #代码本身文件路径，防止脚本文件放在path路径下时，被一起重命名
#             os.rename(os.path.join(path,old_name),os.path.join(path,mark+old_name))  #子文件夹重命名
#             print (old_name,"has been renamed successfully! New name is: ",mark+old_name)
#
# if __name__ == '__main__':
#         path = r'E:\我的学习\编程\Python\PythonTest2\Test2'   #运行程序前，记得修改主文件夹路径！
#         add_prefix_subfolders()            #调用定义的函数


# 然后拼接内容
import os
import sys
import glob

# 首先将所有的gz文件解压出来
# gzip -dv access.log.*.gz


def merger_all_access_log(my_path, sum_log, dir_name='nginx_1_13'):
    '''
    :param my_path:
    :param sum_log:
    :param dir_name:
    :return:
    '''

    # 先把access.log改名为access.log.00
    if os.path.exists(os.path.join(my_path, 'access.log')):
        os.rename(os.path.join(my_path, 'access.log'), os.path.join(my_path, 'access.log.00'))

    # 获取文件夹下所有access.log文件
    path_files_list = glob.glob(pathname=dir_name + '/access.log*')
    print(path_files_list)

    access_log_num = len(path_files_list)
    print(access_log_num)

    for one_file in path_files_list:
        # print(one_file)
        split_list = one_file.split('log.')

        if len(split_list[-1]) == 1:
            new_name = one_file.replace('log.' + split_list[-1], 'log.0' + split_list[-1])
            print(new_name)
            os.rename(one_file, new_name)

    # 获取更改名完成后的所有文件列别
    path_files_list_02 = glob.glob(pathname=dir_name + '/access.log*')
    print(path_files_list_02)

    path_files_list_03 = sorted(path_files_list_02, reverse=True)
    print(path_files_list_03)

    fp01 = open(sum_log, 'a+')
    for one_log in path_files_list_03:
        with open(one_log, 'r') as fp02:
            fp01.write(fp02.read())
    fp01.close()

    print('finish')


if __name__ == '__main__':
    merger_all_access_log(my_path='nginx_1_13', sum_log='nginx_1_13/access_sum.log')
